<template>
  <el-drawer v-model="show">
    <el-form :model="props.row" label-width="120" :rules="rules" ref="formRef">
      <el-form-item label="emoji" prop="emoji">
        <el-input v-model="props.row.emoji"></el-input>
      </el-form-item>
      <el-form-item label="文字显示" prop="text_show">
        <el-input v-model="props.row.text_show" placeholder="比如:[开心],必须包含[]括号,括号内字数不可超过5个"></el-input>
      </el-form-item>
      <el-form-item label="排序值">
        <el-input-number v-model="props.row.sort" :max="1000" :min="1"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="confirm">提交</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref } from "vue";
interface Props {
  row: {
    id?: number;
    text_show: string;
    emoji: string;
    sort: number;
  };
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}
const show = ref(false);
const props = ref<Props>({
  row: {
    text_show: "",
    emoji: "",
    sort: 100
  }
});
const validateTextShow = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error("不可为空"));
  if (!/^\[.{1,5}\]$/.test(value)) return callback(new Error("格式错误"));
  callback();
};
const rules: FormRules = {
  emoji: [
    { required: true, message: "emoji不可为空", trigger: "blur" },
    { max: 2, min: 1, message: "不可超过20个字", trigger: "blur" }
  ],
  text_show: [
    { required: true, message: "文字显示不可为空", trigger: "blur" },
    { validator: validateTextShow, trigger: "blur" }
  ]
};
const open = (params: Props) => {
  props.value = params;
  show.value = true;
};

const formRef = ref<FormInstance>();
const confirm = () => {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await props.value.api!(props.value.row);
      ElMessage.success("成功");
      await props.value.getTable!();
      show.value = false;
    } catch (error) {}
  });
};

defineExpose({ open });
</script>
<style></style>
